import React, { Component } from 'react';
import PropTypes from 'prop-types';
import InfiniteScroll from './InfiniteScroll.js';
import WorkThumbnail from './WorkThumbnail.js';

export default class WorksScrollList extends Component {
  constructor(props) {
    super(props);
    this.loadItems = this.loadItems.bind(this);
    this.hasMore = this.hasMore.bind(this);
    this.state = {
      pageId: -1,
      limit: 20,
    };
  }

  loadItems() {
    let { pageId, limit, workList } = this.state;
    workList = workList || [];
    const { loadPage } = this.props;
    loadPage(pageId + 1, limit).then((data) => {
      this.setState({
        pageId: pageId + 1,
        limit,
        workList: workList.concat(data.assetList),
        totalCount: data.totalCount,
      });
    });
  }

  hasMore() {
    const { workList, totalCount } = this.state;
    if (workList === undefined || totalCount === undefined) {
      return true;
    }
    return workList.length < totalCount;
  }

  renderDummyElements() {
    const dummies = [1, 2, 3, 4, 5, 6, 7];
    return dummies.map(dmy => <div key={dmy} className="thumb-item dummy" />);
  }

  render() {
    const loader = <div className="loading"><i className=" icon-spinner2" />正在加载...</div>;
    const items = this.state.workList && this.state.workList.map(work => <WorkThumbnail key={work.id} work={work} />);

    return (
      <InfiniteScroll
        pageStart={0}
        loadMore={this.loadItems}
        hasMore={this.hasMore()}
        loader={loader}
        useWindow
      >
        <div className="thumb-list">
          {items}
          {this.renderDummyElements()}
        </div>
      </InfiniteScroll>
    );
  }
}

WorksScrollList.propTypes = {
  workList: PropTypes.array,
  pageId: PropTypes.number,
  limit: PropTypes.number,
  totalCount: PropTypes.number,
  loadPage: PropTypes.func,
};
